#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <signal.h>
#include <sys/select.h>

int create_tcp_server_socket(char *ip, int port)
{
    signal(SIGPIPE, SIG_IGN);

    int sockfd;
    int sockaddr_len;

    struct in_addr server_ip;
    struct sockaddr_in server_addr;
    // 1、socket函数创建套接字 -->  文件描述符
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1)
    {
        perror("socket create failed!\n");
        exit(1);
    }
    printf("socket create Success! %d\n", sockfd);

    int reuse = 1;
    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));

    //??为什么要绑定IP和端口号？接受客户端的连接，就需要确定服务器的IP和端口号
    // 2、bind：给套接字绑定IP地址和端口号
    // 初始化struct sockadd_in变量；

    inet_pton(AF_INET, ip, (void *)&server_ip);
    server_addr.sin_family = AF_INET;   // IPV4
    server_addr.sin_addr = server_ip;   // IP
    server_addr.sin_port = htons(port); // h:host to n:net

    if (bind(sockfd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr_in)) < 0)
    {
        perror("bind ip & port failed!");
        exit(1);
    }
    printf("bind Success ip = %s port = %d\n", ip, port);

    // 3、listen：监听：允许其他人进行连接请求
    if (listen(sockfd, 20) < 0)
    {
        perror("listen failed!\n");
        exit(1);
    }
    printf("listen Success!\n");

    return sockfd;
}

void setnonblock(int sockfd)
{
    int flags = fcntl(sockfd, F_GETFL);
    flags = flags | O_NONBLOCK;
    fcntl(sockfd, F_SETFL, flags);
}

int main(int argc, char **argv)
{
    if (argc != 3)
    {
        printf("Please input server bind ip and port!\n");
        exit(1);
    }

    int fd;
    int sockfd;
    int r_len;
    int rnums;
    int confd;
    int tempfd;
    int sockaddr_len;
    char message[1024] = {0};
    char client_ip[INET_ADDRSTRLEN];
    struct sockaddr_in client_addr;

    // 1、定义监听的集合fd_set
    fd_set rset;
    fd_set all_set;
    // 2、定义maxfd
    int maxfd = 0;
    // 3、定义保存连接成功的客户端对应的文件描述符

    int client_fds[__FD_SETSIZE];
    for (int i = 0; i < __FD_SETSIZE; i++)
    {
        client_fds[i] = -1;
    }

    sockfd = create_tcp_server_socket(argv[1], atoi(argv[2]));
    FD_SET(sockfd, &all_set);
    maxfd = maxfd > sockfd ? maxfd : sockfd;
    // select:sockfd:当有客户端连接服务器时，sockfd呈现读状态

    // 4、accept: 处理连接请求：三次握手
    while (1)
    {
        // 1.select
        rset = all_set;
        printf("selecting!\n");
        rnums = select(maxfd + 1, &rset, NULL, NULL, 0);
        if (rnums < 0)
        {
            perror("select error!");
            break;
        }
        printf("enable read fd nums = [%d]\n", rnums);
        
        //判断是否是新的连接
        if (FD_ISSET(sockfd, &rset))
        {
            sockaddr_len = sizeof(struct sockaddr);
            // confd:连接描述符（文件描述符） 每成功连接一个客户端，对应生成唯一的连接描述符
            confd = accept(sockfd, (struct sockaddr *)&client_addr, (socklen_t *)&sockaddr_len);
            // select：confd：当客户端给服务器发送数据式，呈现读状态；
            if (confd < 0)
            {
                perror("accept failed!");
                exit(1);
            }
            else
            {
                inet_ntop(AF_INET, &client_addr.sin_addr, client_ip, sizeof(client_ip));
                printf("client ip = %s port = %d\n", client_ip, client_addr.sin_port);
                FD_SET(confd, &all_set);

                for(int i = 0; i < __FD_SETSIZE; i++)
                {
                    if(client_fds[i] == -1)
                    {
                        client_fds[i] = confd;
                        break;
                    }
                }

                maxfd = maxfd > confd ? maxfd : confd;

                if(--rnums == 0)
                {
                    continue;
                }
            }
        }
        
        //判断哪个连接描述符有数据可读
        for(int i = 0; i < __FD_SETSIZE; i++)
        {
            if((fd = client_fds[i]) != -1)
            {
                if(FD_ISSET(fd, &rset))
                {
                    memset(message, 0, sizeof(message));
                    r_len = read(fd, message, sizeof(message));

                    if(r_len < 0)
                    {
                        perror("read data error!\n");
                        continue;
                    }
                    if(r_len == 0)
                    {
                        printf("client is close!\n");
                        client_fds[i] = -1;
                        FD_CLR(fd, &all_set);
                        close(fd);
                    }
                    else if(r_len > 0)
                    {
                        message[r_len] = '\0';
                        printf("recv client data:%s\n", message);

                        write(fd, "OK\n", 3);
                    }

                    if(--rnums == 0)
                    {
                        break;
                    }
                }
            }
        }
    }

    // 6、close/shutdown： 关闭连接

    return 0;
}